<template>
    <!-- 因为这里有 v-if v-else , 所以与一个根节点不冲突 -->
    <van-button
        v-if="isFollowed"
        round
        size="small"
        :loading="loading"
        @click="onFollow"
    >已关注</van-button>
    <van-button
        v-else
        type="info"
        color="#3296fa"
        round
        size="small"
        icon="plus"
        :loading="loading"
        @click="onFollow"
    >关注</van-button>
</template>

<script>
import { addFollow ,deleteFollow } from '@/api/user'

export default {
    name: 'FollowUser',
    // model 的作用:自定义 v-model 的数据名称
    model: {
        prop: 'isFollowed',
        event: 'update-is_followed'
    },
    props: {
        isFollowed: {  // 存储是否关注的状态
            type: Boolean,
            required: true
        },
        userId: {  // 文章的id
            type: [Number,String,Object],
            required: true
        }
    },
    data() {
        return {
            loading:false // 关注按钮加载状态
        }
    },
    methods: {
        async onFollow() {
            this.loading = true //展示关注按钮的 loading 状态

            try {
                if (this.isFollowed) {
                    // 已关注，取消关注
                    await deleteFollow(this.userId)
                } else {
                    // 未关注，添加关注
                    await addFollow(this.userId)
                }

                //更新视图状态 
                // this.article.is_followed = !this.article.is_followed
                // this.$emit('update-is_followed',!this.isFollowed)
                // this.$emit('input',!this.value)
                this.$emit('update-is_followed',!this.isFollowed)


            } catch (err) {
                let message = '操作失败，请重试！'
                if (err.response && err.response.status === 400) {
                message = '你不能关注你自己！'
                }
                this.$toast(message)
            }

            this.loading = false //关闭关注按钮的 loading 状态
        }
    }
}
</script>

<style>

</style>